#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int start1,start2,n;
int Data[100000],Next[100000];
vector<int> v1,v2,ans;

signed main()
{
    cin>>start1>>start2>>n;
    for(int i=0;i<n;i++){
        int t;
        cin>>t>>Data[t]>>Next[t];
    }
    while(start1!=-1){
        v1.push_back(start1);
        start1 = Next[start1];
    }
    while(start2!=-1){
        v2.push_back(start2);
        start2 = Next[start2];
    }
    if(v1.size()<v2.size())    swap(v1,v2);
    reverse(v2.begin(),v2.end());
    int i=0,j=0;
    while(i<v1.size()||j<v2.size()){
        if(i%2==1&&j<v2.size()){
            ans.push_back(v1[i++]);
            ans.push_back(v2[j++]);
        }
        else
            ans.push_back(v1[i++]);
    }
    for(i=0;i<ans.size()-1;i++)
        printf("%05d %d %05d\n",ans[i],Data[ans[i]],ans[i+1]);
    printf("%05d %d -1\n",ans[i],Data[ans[i]]);
    return 0;
}
